/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package jpa.controllers;

import entity.Courses;
import java.io.Serializable;
import javax.persistence.Query;
import javax.persistence.EntityNotFoundException;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;
import entity.User;
import entity.Lecture;
import java.util.ArrayList;
import java.util.List;
import entity.Enrollment;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import jpa.controllers.exceptions.IllegalOrphanException;
import jpa.controllers.exceptions.NonexistentEntityException;

/**
 *
 * @author atap
 */
public class CoursesJpaController implements Serializable {

    public CoursesJpaController() {
    }
    
    public CoursesJpaController(EntityManagerFactory emf) {
        this.emf = emf;
    }
    private EntityManagerFactory emf = Persistence.createEntityManagerFactory("EducationXPU");

    public EntityManager getEntityManager() {
        return emf.createEntityManager();
    }

    public void create(Courses courses) {
        if (courses.getLectureList() == null) {
            courses.setLectureList(new ArrayList<Lecture>());
        }
        if (courses.getEnrollmentList() == null) {
            courses.setEnrollmentList(new ArrayList<Enrollment>());
        }
        EntityManager em = null;
        try {
            em = getEntityManager();
            em.getTransaction().begin();
            User createrUserId = courses.getCreaterUserId();
            if (createrUserId != null) {
                createrUserId = em.getReference(createrUserId.getClass(), createrUserId.getId());
                courses.setCreaterUserId(createrUserId);
            }
            List<Lecture> attachedLectureList = new ArrayList<Lecture>();
            for (Lecture lectureListLectureToAttach : courses.getLectureList()) {
                lectureListLectureToAttach = em.getReference(lectureListLectureToAttach.getClass(), lectureListLectureToAttach.getId());
                attachedLectureList.add(lectureListLectureToAttach);
            }
            courses.setLectureList(attachedLectureList);
            List<Enrollment> attachedEnrollmentList = new ArrayList<Enrollment>();
            for (Enrollment enrollmentListEnrollmentToAttach : courses.getEnrollmentList()) {
                enrollmentListEnrollmentToAttach = em.getReference(enrollmentListEnrollmentToAttach.getClass(), enrollmentListEnrollmentToAttach.getId());
                attachedEnrollmentList.add(enrollmentListEnrollmentToAttach);
            }
            courses.setEnrollmentList(attachedEnrollmentList);
            em.persist(courses);
            if (createrUserId != null) {
                createrUserId.getCoursesList().add(courses);
                createrUserId = em.merge(createrUserId);
            }
            for (Lecture lectureListLecture : courses.getLectureList()) {
                Courses oldCourseIdOfLectureListLecture = lectureListLecture.getCourseId();
                lectureListLecture.setCourseId(courses);
                lectureListLecture = em.merge(lectureListLecture);
                if (oldCourseIdOfLectureListLecture != null) {
                    oldCourseIdOfLectureListLecture.getLectureList().remove(lectureListLecture);
                    oldCourseIdOfLectureListLecture = em.merge(oldCourseIdOfLectureListLecture);
                }
            }
            for (Enrollment enrollmentListEnrollment : courses.getEnrollmentList()) {
                Courses oldCourseIdOfEnrollmentListEnrollment = enrollmentListEnrollment.getCourseId();
                enrollmentListEnrollment.setCourseId(courses);
                enrollmentListEnrollment = em.merge(enrollmentListEnrollment);
                if (oldCourseIdOfEnrollmentListEnrollment != null) {
                    oldCourseIdOfEnrollmentListEnrollment.getEnrollmentList().remove(enrollmentListEnrollment);
                    oldCourseIdOfEnrollmentListEnrollment = em.merge(oldCourseIdOfEnrollmentListEnrollment);
                }
            }
            em.getTransaction().commit();
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public void edit(Courses courses) throws IllegalOrphanException, NonexistentEntityException, Exception {
        EntityManager em = null;
        try {
            em = getEntityManager();
            em.getTransaction().begin();
            Courses persistentCourses = em.find(Courses.class, courses.getCourseId());
            User createrUserIdOld = persistentCourses.getCreaterUserId();
            User createrUserIdNew = courses.getCreaterUserId();
            List<Lecture> lectureListOld = persistentCourses.getLectureList();
            List<Lecture> lectureListNew = courses.getLectureList();
            List<Enrollment> enrollmentListOld = persistentCourses.getEnrollmentList();
            List<Enrollment> enrollmentListNew = courses.getEnrollmentList();
            List<String> illegalOrphanMessages = null;
            for (Enrollment enrollmentListOldEnrollment : enrollmentListOld) {
                if (!enrollmentListNew.contains(enrollmentListOldEnrollment)) {
                    if (illegalOrphanMessages == null) {
                        illegalOrphanMessages = new ArrayList<String>();
                    }
                    illegalOrphanMessages.add("You must retain Enrollment " + enrollmentListOldEnrollment + " since its courseId field is not nullable.");
                }
            }
            if (illegalOrphanMessages != null) {
                throw new IllegalOrphanException(illegalOrphanMessages);
            }
            if (createrUserIdNew != null) {
                createrUserIdNew = em.getReference(createrUserIdNew.getClass(), createrUserIdNew.getId());
                courses.setCreaterUserId(createrUserIdNew);
            }
            List<Lecture> attachedLectureListNew = new ArrayList<Lecture>();
            for (Lecture lectureListNewLectureToAttach : lectureListNew) {
                lectureListNewLectureToAttach = em.getReference(lectureListNewLectureToAttach.getClass(), lectureListNewLectureToAttach.getId());
                attachedLectureListNew.add(lectureListNewLectureToAttach);
            }
            lectureListNew = attachedLectureListNew;
            courses.setLectureList(lectureListNew);
            List<Enrollment> attachedEnrollmentListNew = new ArrayList<Enrollment>();
            for (Enrollment enrollmentListNewEnrollmentToAttach : enrollmentListNew) {
                enrollmentListNewEnrollmentToAttach = em.getReference(enrollmentListNewEnrollmentToAttach.getClass(), enrollmentListNewEnrollmentToAttach.getId());
                attachedEnrollmentListNew.add(enrollmentListNewEnrollmentToAttach);
            }
            enrollmentListNew = attachedEnrollmentListNew;
            courses.setEnrollmentList(enrollmentListNew);
            courses = em.merge(courses);
            if (createrUserIdOld != null && !createrUserIdOld.equals(createrUserIdNew)) {
                createrUserIdOld.getCoursesList().remove(courses);
                createrUserIdOld = em.merge(createrUserIdOld);
            }
            if (createrUserIdNew != null && !createrUserIdNew.equals(createrUserIdOld)) {
                createrUserIdNew.getCoursesList().add(courses);
                createrUserIdNew = em.merge(createrUserIdNew);
            }
            for (Lecture lectureListOldLecture : lectureListOld) {
                if (!lectureListNew.contains(lectureListOldLecture)) {
                    lectureListOldLecture.setCourseId(null);
                    lectureListOldLecture = em.merge(lectureListOldLecture);
                }
            }
            for (Lecture lectureListNewLecture : lectureListNew) {
                if (!lectureListOld.contains(lectureListNewLecture)) {
                    Courses oldCourseIdOfLectureListNewLecture = lectureListNewLecture.getCourseId();
                    lectureListNewLecture.setCourseId(courses);
                    lectureListNewLecture = em.merge(lectureListNewLecture);
                    if (oldCourseIdOfLectureListNewLecture != null && !oldCourseIdOfLectureListNewLecture.equals(courses)) {
                        oldCourseIdOfLectureListNewLecture.getLectureList().remove(lectureListNewLecture);
                        oldCourseIdOfLectureListNewLecture = em.merge(oldCourseIdOfLectureListNewLecture);
                    }
                }
            }
            for (Enrollment enrollmentListNewEnrollment : enrollmentListNew) {
                if (!enrollmentListOld.contains(enrollmentListNewEnrollment)) {
                    Courses oldCourseIdOfEnrollmentListNewEnrollment = enrollmentListNewEnrollment.getCourseId();
                    enrollmentListNewEnrollment.setCourseId(courses);
                    enrollmentListNewEnrollment = em.merge(enrollmentListNewEnrollment);
                    if (oldCourseIdOfEnrollmentListNewEnrollment != null && !oldCourseIdOfEnrollmentListNewEnrollment.equals(courses)) {
                        oldCourseIdOfEnrollmentListNewEnrollment.getEnrollmentList().remove(enrollmentListNewEnrollment);
                        oldCourseIdOfEnrollmentListNewEnrollment = em.merge(oldCourseIdOfEnrollmentListNewEnrollment);
                    }
                }
            }
            em.getTransaction().commit();
        } catch (Exception ex) {
            String msg = ex.getLocalizedMessage();
            if (msg == null || msg.length() == 0) {
                Integer id = courses.getCourseId();
                if (findCourses(id) == null) {
                    throw new NonexistentEntityException("The courses with id " + id + " no longer exists.");
                }
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public void destroy(Integer id) throws IllegalOrphanException, NonexistentEntityException {
        EntityManager em = null;
        try {
            em = getEntityManager();
            em.getTransaction().begin();
            Courses courses;
            try {
                courses = em.getReference(Courses.class, id);
                courses.getCourseId();
            } catch (EntityNotFoundException enfe) {
                throw new NonexistentEntityException("The courses with id " + id + " no longer exists.", enfe);
            }
            List<String> illegalOrphanMessages = null;
            List<Enrollment> enrollmentListOrphanCheck = courses.getEnrollmentList();
            for (Enrollment enrollmentListOrphanCheckEnrollment : enrollmentListOrphanCheck) {
                if (illegalOrphanMessages == null) {
                    illegalOrphanMessages = new ArrayList<String>();
                }
                illegalOrphanMessages.add("This Courses (" + courses + ") cannot be destroyed since the Enrollment " + enrollmentListOrphanCheckEnrollment + " in its enrollmentList field has a non-nullable courseId field.");
            }
            if (illegalOrphanMessages != null) {
                throw new IllegalOrphanException(illegalOrphanMessages);
            }
            User createrUserId = courses.getCreaterUserId();
            if (createrUserId != null) {
                createrUserId.getCoursesList().remove(courses);
                createrUserId = em.merge(createrUserId);
            }
            List<Lecture> lectureList = courses.getLectureList();
            for (Lecture lectureListLecture : lectureList) {
                lectureListLecture.setCourseId(null);
                lectureListLecture = em.merge(lectureListLecture);
            }
            em.remove(courses);
            em.getTransaction().commit();
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public List<Courses> findCoursesEntities() {
        return findCoursesEntities(true, -1, -1);
    }

    public List<Courses> findCoursesEntities(int maxResults, int firstResult) {
        return findCoursesEntities(false, maxResults, firstResult);
    }

    private List<Courses> findCoursesEntities(boolean all, int maxResults, int firstResult) {
        EntityManager em = getEntityManager();
        try {
            CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
            cq.select(cq.from(Courses.class));
            Query q = em.createQuery(cq);
            if (!all) {
                q.setMaxResults(maxResults);
                q.setFirstResult(firstResult);
            }
            return q.getResultList();
        } finally {
            em.close();
        }
    }

    public Courses findCourses(Integer id) {
        EntityManager em = getEntityManager();
        try {
            return em.find(Courses.class, id);
        } finally {
            em.close();
        }
    }

    public int getCoursesCount() {
        EntityManager em = getEntityManager();
        try {
            CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
            Root<Courses> rt = cq.from(Courses.class);
            cq.select(em.getCriteriaBuilder().count(rt));
            Query q = em.createQuery(cq);
            return ((Long) q.getSingleResult()).intValue();
        } finally {
            em.close();
        }
    }
    
}
